package com.mybatis.icbatuis.proxy;

import com.mybatis.bean.Dept;
import com.mybatis.icbatuis.ICSql;

import javax.sql.DataSource;
import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Type;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

/**
 * -- Created by IntelliJ IDEA.
 * -- REMARK:
 * -- User: tanwei
 * -- Date: 2021/3/5
 * -- Time: 6:45 下午
 * --
 */
public class ItemProxy<T> implements InvocationHandler {



    DataSource dataSource;

    public ItemProxy(DataSource dataSource) {
        this.dataSource = dataSource;
    }

    @Override
    public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {

        //目标方法执行
        ICSql sql = method.getAnnotation(ICSql.class);
        String value = sql.value();

        //获取连接
        Connection connection = dataSource.getConnection();

        //2、创建
//        Statement statement = connection.createStatement();

        // PreparedStatement 预编译sql
        PreparedStatement preparedStatement = connection.prepareStatement(value);

//        for (int i = 0; i < args.length; i++) {
//            //大量反射判断
//            preparedStatement.setInt(1, 3);
//
//        }

        preparedStatement.setInt(1, Integer.parseInt(args[0].toString()));
        ResultSet resultSet = preparedStatement.executeQuery();
        Dept dept=null;
        while (resultSet.next()) {
            int deptno = resultSet.getInt(1);
            String dname = resultSet.getString(2);
            String dbSource = resultSet.getString(3);
            dept = new Dept(deptno, dname, dbSource);
        }

//        System.out.println(depts);
        connection.close();

//        int i = 0;
//        while (value.contains("?")) {
//            value = value.replaceFirst("\\?", args[i].toString());
//            i++;
//        }
//        System.out.println("执行了目标方法" + method.getName());
//        System.out.println("参数列表：" + Arrays.asList(args));
//        System.out.println("预编译sql" + value);
//        //执行sql
//        Type genericReturnType = method.getGenericReturnType();
//        System.out.println("方法返回值：" + genericReturnType.getTypeName());
        return dept;
    }
}
